package com.ruoyi.web.controller.store;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.StoreUserRole;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.product.domain.StoreProduct;
import com.ruoyi.product.domain.StoreProductBack;
import com.ruoyi.product.service.IStoreProductBackService;
import com.ruoyi.product.service.IStoreProductService;
import com.ruoyi.richEditor.domain.RichEditorAttachment;
import com.ruoyi.richEditor.service.IRichEditorAttachmentService;
import com.ruoyi.storeclassify.domain.Storeclassify;
import com.ruoyi.storeclassify.service.IStoreclassifyService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.store.domain.Store;
import com.ruoyi.store.service.IStoreService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.swing.*;

/**
 * 门店Controller
 *
 * @author ruoyi
 * @date 2021-11-17
 */
@RestController
@RequestMapping("/admin/store/store")
public class StoreController extends BaseController
{
    @Autowired
    private IStoreService storeService;

    @Autowired
    private IRichEditorAttachmentService richEditorService;

    @Autowired
    private IStoreclassifyService classifyService;

    @Autowired
    private IStoreProductBackService backService;

    @Autowired
    private IStoreProductService productService;

    /**
     * 查询富文本
     * */
    @GetMapping("/getRichAtt/{id}")
    public AjaxResult getRichAdd(@PathVariable Long id ){
        return AjaxResult.success(richEditorService.selectRichEditorAttachmentById(id));
    }

    /**
     * 增加富文本
     * */
    @PostMapping("/richAdd")
    public RichEditorAttachment richAdd(@RequestBody RichEditorAttachment attachment){
        attachment.setAnyId(getUserId());
        richEditorService.insertRichEditorAttachment(attachment);
        return attachment;
    }

    /**
     * 修改富文本
     * */
    @PutMapping("/richEdit")
    public int richEdit(@RequestBody RichEditorAttachment attachment){
        return richEditorService.updateRichEditorAttachment(attachment);
    }

    /**
     * 查询团购商品
     * */
    @GetMapping("/getStoreProduct/{id}")
    public AjaxResult getStoreProduct(@PathVariable Long id ){
        return AjaxResult.success(productService.selectStoreProductById(id));
    }

    /**
     * 添加团购商品
     * */
    @PutMapping("/addStoreProduct")
    public StoreProduct addStoreProduct(@RequestBody StoreProduct product){
        RichEditorAttachment richEditorAttachment = richEditorService.selectRichEditorAttachmentById(product.getInfoId());
        //Store store = storeService.selectStoreById(product.getStoreId());
        Storeclassify storeclassify = classifyService.selectStoreclassifyById(product.getClassifyId());
//        product.setService(store.getServiceItem());
        product.setClassifyParentId(storeclassify.getParentId());
//        product.setStoreId(store.getId());
//        product.setStoreName(store.getStoreName());
//        product.setProvinceName(store.getProvinceName());
//        product.setProvinceCode(store.getProvinceCode());
//        product.setCityName(store.getCityName());
//        product.setCityCode(store.getCityCode());
//        product.setLatitude(store.getLatitude());
//        product.setLongitude(store.getLongitude());
//        product.setGeoCode(store.getGeoCode());
        product.setSalesNum(0L);
        product.setCreateBy(getUserId());
//        product.setAdCode(store.getAdCode());
//        product.setAdName(store.getAdName());
        product.setCreateType(DicConstants.BUSINESS_Business.getCode());
        product.setState(DicConstants.SYS_N.getCode());
        StoreProductBack back = new StoreProductBack(product,richEditorAttachment.getAttValue());
        back.setCreateBy(getUserId());
        back.setCreateType(DicConstants.BUSINESS_Business.getCode());
        backService.insertStoreProductBack(back);
        product.setProductBackId(back.getId());
        productService.insertStoreProduct(product);
        back.setProductId(product.getId());
        backService.updateStoreProductBack(back);
        return product;
    }

    /**
     * 修改团购商品
     * */
    @PutMapping("/updateStoreProduct")
    public StoreProduct updateStoreProduct(@RequestBody StoreProduct product){
        RichEditorAttachment richEditorAttachment = richEditorService.selectRichEditorAttachmentById(product.getInfoId());
        product.setCreateType(DicConstants.BUSINESS_Business.getCode());
        product.setState(DicConstants.SYS_N.getCode());
        StoreProductBack back = new StoreProductBack(product,richEditorAttachment.getAttValue());
        back.setCreateBy(getUserId());
        back.setCreateType(DicConstants.BUSINESS_Business.getCode());
        backService.insertStoreProductBack(back);
        product.setProductBackId(back.getId());
        productService.updateStoreProduct(product);
        return product;
    }

    /**
     * 查询门店列表
     */
    @PreAuthorize("@ss.hasPermi('store:store:list')")
    @GetMapping("/list")
    public TableDataInfo list(Store store)
    {
        startPage();
        List<Store> list = storeService.selectStoreList(store);
        for(Store store1:list){
            store1.setStoreStaffCount(storeService.selectStoreStaffCount(store1.getId()));
            store1.setStoreOrderCount(storeService.selectStoreOrderCount(store1.getId()));
            store1.setStoreRevenue(storeService.selectStoreRevenue(store1.getId()));
        }
        return getDataTable(list);
    }

    /**
     * 查询门店列表(作为参数)
     */
    @GetMapping("/storeListParam")
    public ArrayList<SysDictData> storeList()
    {
//        ArrayList<HashMap<Long, String>> maps = new ArrayList<HashMap<Long, String>>();
        ArrayList<SysDictData> maps = new ArrayList<>();
        List<Store> stores = storeService.selectStoreList(new Store());
        if(stores.size() == 0)
            return maps;
        stores.forEach(e->{
            SysDictData sysDictData = new SysDictData();
            sysDictData.setDictLabel(e.getStoreName());
            sysDictData.setDictValue(e.getId().toString());
            maps.add(sysDictData);
        });
        return maps;
    }
    /**
     * 导出门店列表
     */
    @PreAuthorize("@ss.hasPermi('store:store:export')")
    @Log(title = "门店", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Store store)
    {
        List<Store> list = storeService.selectStoreList(store);
        ExcelUtil<Store> util = new ExcelUtil<Store>(Store.class);
        return util.exportExcel(list, "门店数据");
    }

    /**
     * 获取门店详细信息
     */
    @PreAuthorize("@ss.hasPermi('store:store:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(storeService.selectStoreById(id));
    }

    /**
     * 新增门店
     */
    @PreAuthorize("@ss.hasPermi('store:store:add')")
    @Log(title = "门店", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Store store)
    {
        return toAjax(storeService.insertStore(store));
    }

    /**
     * 修改门店
     */
    @PreAuthorize("@ss.hasPermi('store:store:edit')")
    @Log(title = "门店", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Store store)
    {
        store.setUpdateType(DicConstants.BUSINESS_Manager.getCode());
        return toAjax(storeService.updateStore(store));
    }

    /**
     * 修改邀请码
     */
    @PreAuthorize("@ss.hasPermi('store:store:edit')")
    @Log(title = "修改邀请码", businessType = BusinessType.UPDATE)
    @PutMapping("/updateAgentCode")
    public AjaxResult updateAgentCode(@RequestBody Store store)
    {
        Store updateStore = new Store();
        updateStore.setId(store.getId());
        updateStore.setAgentCode(store.getAgentCode());
        updateStore.setUpdateType(DicConstants.BUSINESS_Manager.getCode());
        updateStore.setUpdateBy(getUserId());
        return toAjax(storeService.updateStore(updateStore));
    }

    /**
     * 删除门店
     */
    @PreAuthorize("@ss.hasPermi('store:store:remove')")
    @Log(title = "门店", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(storeService.logicDeleteStore(ids,DicConstants.BUSINESS_Manager.getCode(),SecurityUtils.getUserId()));
    }


    /**
     * 门店展示管理-增
     */
    @PreAuthorize("@ss.hasPermi('store:store:addImage')")
    @Log(title = "门店展示管理-增", businessType = BusinessType.INSERT)
    @PostMapping("/addImage")
    public AjaxResult addImage(Long storeId,String image)
    {
            Store store=storeService.selectStoreById(storeId);

            String images = store.getStoreShowImage();
            if(images==null)
            {
                images=image;
            }
            if(images!=null)
            {
                images+=","+image;
            }
            store.setStoreShowImage(images);
            store.setUpdateBy(getUserId());
            store.setUpdateType(DicConstants.BUSINESS_Manager.getCode());
            return toAjax(storeService.updateStore(store));
    }


    /**
     * 门店展示管理-删
     */
    @PreAuthorize("@ss.hasPermi('store:store:removeImage')")
    @Log(title = "门店展示管理-删", businessType = BusinessType.DELETE)
    @PostMapping("/removeImage")
    public AjaxResult removeImage(@RequestParam("storeId")Long storeId, @RequestParam("deleteImage")String deleteImage)
    {
        Store store=storeService.selectStoreById(storeId);
        String images=store.getStoreShowImage();
        String[] imageArray = images.split(",");
        // 将字符串数组转换为ArrayList，以便支持removeIf操作
        List<String> imageList = new ArrayList<>(Arrays.asList(imageArray));
        // 移除要删除的图片
        imageList.removeIf(image -> image.equals(deleteImage));
        // 将修改后的List转换回逗号分隔的字符串
        String updatedImages = imageList.stream().collect(Collectors.joining(","));
        store.setStoreShowImage(updatedImages);
        store.setUpdateBy(getUserId());
        store.setUpdateType(DicConstants.BUSINESS_Manager.getCode());
        return toAjax(storeService.updateStore(store));

    }

    /**
     * 门店展示管理-改
     */
    @PreAuthorize("@ss.hasPermi('store:store:editImage')")
    @Log(title = "门店展示管理-改", businessType = BusinessType.UPDATE)
    @PostMapping("/editImage")
    public AjaxResult editImage(@RequestBody Store store)
    {
        store.setUpdateBy(getUserId());
        store.setUpdateType(DicConstants.BUSINESS_Manager.getCode());
        return toAjax(storeService.updateStore(store));
    }

}
